package com.dgw.springbootsolr.controller;

import com.dgw.springbootsolr.config.SolrConfig;
import com.dgw.springbootsolr.entity.Admin;
import com.dgw.springbootsolr.entity.Goods;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: springboot-solr
 * @description:
 * @author: Mr.Dai
 * @create: 2020-02-26 21:09
 **/
@RestController
public class SolrController {

    @Autowired
    public SolrClient solrClient;

    @Autowired
    private SolrConfig solrConfig;

    //http://localhost:8080/saveOrUpdate?id=1&name=dgw&age=24
    @GetMapping("saveOrUpdate")
    public String saveOrUpdate(Admin admin) {
        if (admin.getId() == null) {
            admin.setId(System.currentTimeMillis());
        }
        try {
            final SolrInputDocument doc = new SolrInputDocument();
            doc.setField("id", admin.getId());
            doc.setField("name", admin.getName());
            doc.setField("age", admin.getAge());
            // collectionName 文档名称
            solrClient.add(solrConfig.collectionName, doc);
            solrClient.commit(solrConfig.collectionName);
            return admin.toString();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 根据id删除索引
     * //http://localhost:8080/delete?id=1
     */
    @GetMapping("delete")
    public String delete(String id) {
        try {
            solrClient.deleteById(solrConfig.collectionName, id);
            solrClient.commit(solrConfig.collectionName);
            return id;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 删除所有的索引
     * http://localhost:8080/deleteAll
     */
    @GetMapping("deleteAll")
    public String deleteAll() {
        try {
            solrClient.deleteByQuery(solrConfig.collectionName, "*:*");
            solrClient.commit(solrConfig.collectionName);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 根据id查询索引
     * http://localhost:8080/getGoodsById?id=1
     */
    @GetMapping("getGoodsById")
    public String getGoodsById(String id) throws Exception {
        SolrDocument document = solrClient.getById(solrConfig.collectionName, id);
        return document.toString();
    }

    //http://localhost:8080/addBean
    @GetMapping("addBean")
    public String addBean() {
        Admin dgw2 = new Admin(1L, "dgw2", 25);
        try {
            solrClient.addBean(solrConfig.collectionName, dgw2);
            solrClient.commit(solrConfig.collectionName);
        } catch (IOException | SolrServerException e) {
            e.printStackTrace();
        }
        return "error";
    }

    // http://localhost:8080/search
    @GetMapping("search")
    public Map<String, Object> search() {
        final SolrQuery solrQuery = new SolrQuery("*:*");
        solrQuery.addField("id");
        solrQuery.addField("name");
        solrQuery.addField("age");
        solrQuery.setSort("id", SolrQuery.ORDER.asc);


        //设置高亮前缀
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        //设置高亮后缀
        solrQuery.setHighlightSimplePost("</span>");

        //指定高亮域
        solrQuery.addHighlightField("id");
        solrQuery.addHighlightField("name");
        solrQuery.setHighlightFragsize(1);
        //打开开关
        solrQuery.setHighlight(true);

        //返回集合
        Map<String, Object> returnMap = new HashMap(16);
        try {
            QueryResponse query = solrClient.query(solrConfig.collectionName, solrQuery);

            SolrDocumentList results = query.getResults();
            //返回行数
            long numFound = results.getNumFound();
            //获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
            Map<String, Map<String, List<String>>> highlight = query.getHighlighting();
            System.out.println(results);
            System.out.println(highlight);
            results.forEach(result -> {
                Map map = highlight.get(result.get("id"));
                result.addField("nameHH", map.get("name"));
            });
            returnMap.put("results", results);
            return returnMap;
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return new HashMap<String, Object>() {
            {
                put("id", "1");
                put("name", "ggg");
                put("age", "12");
            }
        };
    }

    /**
     * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息
     *
     * @return
     */
    @GetMapping("search2")
    public Map<String, Object> search2(String keyword) {
        //返回集合
        Map<String, Object> returnMap = new HashMap();
        try {
            SolrQuery params = new SolrQuery();
            //查询条件
            params.set("q", keyword);
            //过滤条件
            params.set("fq", "goodsPrice:[100 TO 100000]");
            //排序
            params.addSort("id", SolrQuery.ORDER.asc);
            //分页
            //从第几条记录开始
            params.setStart(0);
            //最多返回多少条记录
            params.setRows(20);
            //默认域
            params.set("df", "goodsIntroduce");
            //只查询指定域
            params.set("fl", "id,goodsName,goodsIntroduce,goodsPrice");
            //高亮
            //打开开关
            params.setHighlight(true);
            //指定高亮域
            params.addHighlightField("goodsIntroduce");
            params.addHighlightField("goodsName");
            //设置高亮前缀
            params.setHighlightSimplePre("<span style='color:red'>");
            //设置高亮后缀
            params.setHighlightSimplePost("</span>");
            QueryResponse queryResponse = solrClient.query(solrConfig.collectionName, params);
            SolrDocumentList results = queryResponse.getResults();
            //返回行数
            long numFound = results.getNumFound();
            //获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
            Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting();
            results.forEach(result -> {
                Map map = highlight.get(result.get("id"));
                result.addField("goodsNameHH", map.get("goodsName"));
                result.addField("goodsIntroduceHH", map.get("goodsIntroduce"));
            });
            returnMap.put("numFound", numFound);
            returnMap.put("results", results);
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //http://localhost:8080/test
    @GetMapping("/test")
    public String test() {
        //System.out.println(solrConfig.collectionName);
        return solrConfig.collectionName;
    }
}
